#include "Unit_Create.h"

#include "../Game.h"
#include "../GameControl.h"
#include "../../tools/Log.h"

#include <cstring>

string Unit_Create::command = "create unit";

string Unit_Create::toString() { return string(serialize().data); }

Unit_Create::Unit_Create(char Type[], unsigned X, unsigned Y)
{
	memcpy(type, Type, 32);
	x = X;
	y = Y;
}

SerializedGameCommand Unit_Create::serialize() const
{
	SerializedGameCommand cmd;
	sprintf(cmd.data, "%s %s %u %u %lu", command.c_str(), type, x, y, timestamp);
	return cmd;
}

Unit_Create* Unit_Create::interpret(const SerializedGameCommand& sgc)
{
	if (strncmp(sgc.data, command.c_str(), command.size()) == 0)
	{
		Unit_Create* cmd = new Unit_Create();
		if(sscanf(sgc.data, "create unit %s %u %u %lu", cmd->type, &(cmd->x), &(cmd->y), &(cmd->timestamp)) == 4) {
			lout << "Yes!" << endl;
			return cmd;
		}
		else
			lout << "Nope." << endl;
	}
	
	return NULL;
}

Unit_Create* Unit_Create::interpret(const char* line)
{
	if (strncmp(line, command.c_str(), command.size()) == 0)
	{
		Unit_Create* cmd = new Unit_Create();
		if(sscanf(line, "create unit %s %u %u %lu", cmd->type, &(cmd->x), &(cmd->y), &(cmd->timestamp)) == 4)
			return cmd;
		else if(sscanf(line, "create unit %s %u %u", cmd->type, &(cmd->x), &(cmd->y)) == 3)
			return cmd;
		
		lout << Unit_Create::command << " error: Invalid arguments" << endl;
		delete cmd;
	}
	
	return NULL;
}

void Unit_Create::onExecute()
{
	// -- BEGIN CUSTOM CODE REGION -- //
	Game::Instance()->create_unit(type, x, y);
	// -- END CUSTOM CODE REGION -- //
}
